/**
 * Copyright (c) 2010 BullionXpress.com,
 * Permission is hereby granted, free of charge, to any person obtaining
 * a copy of this software and associated documentation files (the
 * "Software"), to deal in the Software without restriction, including
 * without limitation the rights to use, copy, modify, merge, publish,
 * distribute, sublicense, and/or sell copies of the Software, and to
 * permit persons to whom the Software is furnished to do so, subject to
 * the following conditions:
 *
 * The above copyright notice and this permission notice shall be
 * included in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 *
 */
package com.bullionxpress.client.view;

import com.bullionxpress.shared.util.Log;
import java.awt.BorderLayout;
import java.text.DecimalFormat;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.TableColumnModel;
import com.bullionxpress.client.application.ClientGlobals;
import com.bullionxpress.shared.model.Instrument;
import com.bullionxpress.shared.model.Position;
import com.bullionxpress.shared.model.Quote;
import com.bullionxpress.shared.listeners.AccountEvent;
import com.bullionxpress.shared.listeners.AccountListener;
import com.bullionxpress.shared.service.PositionService;
import com.bullionxpress.shared.service.QuoteService;
import java.util.Hashtable;

/**
 *
 * @author BullionXpress.com
 */
public class PositionListView extends JPanel implements AccountListener {

    JTable table = null;
    GenericTableModel model = new GenericTableModel();
    private static final int POSITION_ID = 0;
    private static final int UNITS = 1;
    private static final int ENTRY_PRICE = 2;
    private static final int INSTRUMENT = 3;
    private static final int PNL = 4;
    //private static final int BOOK_VALUE   = 5;
    private static final int MARKET_VALUE = 5;

    public PositionListView() {
        //this.account = account;
        ClientGlobals.cm.addAccountListener(this);
        //String[] columnNames = new String[]{"Position ID", "Units", "Entry Price", "Instrument", "PnL", "Book Value", "Market Value"}; // BALANCE ?
        String[] columnNames = new String[]{"Position ID", "Units", "Average Entry Price", "Instrument", "PnL", "Market Value"}; // BALANCE ?
        for (int i = 0; i < columnNames.length; i++) {
            model.addColumn(columnNames[i]);
        }
        table = new JTable(model);
        //TODO: REFACTOR
        TableColumnModel tcm = table.getColumnModel();
        tcm.getColumn(UNITS).setCellRenderer(new NumberCellRenderer());
        tcm.getColumn(ENTRY_PRICE).setCellRenderer(new DollarCellRenderer());
        tcm.getColumn(PNL).setCellRenderer(new DollarCellRenderer());
        //tcm.getColumn(BOOK_VALUE).setCellRenderer(new DollarCellRenderer());
        tcm.getColumn(MARKET_VALUE).setCellRenderer(new DollarCellRenderer());

        setLayout(new BorderLayout());
        add(table.getTableHeader(), BorderLayout.NORTH);
        JScrollPane scrollPane = new JScrollPane(table);
        add(scrollPane, BorderLayout.CENTER);
    }

    public boolean containsPosition(String pid) {
        try {
            for (int i = 0; i < model.getRowCount(); i++) {
                String id = (String) model.getValueAt(i, INSTRUMENT);
                if (id.equals(pid)) {
                    return true;
                }
            }
        } catch (Exception ex) {
        }
        return false;
    }

    private int getPositionRow(String symbol) {
        for (int i = 0; i < model.getRowCount(); i++) {
            String v = (String) model.getValueAt(i, INSTRUMENT);
            if (symbol.equals(v)) {
                return i;
            }
        }
        return -1;
    }

    private void updatePosition(Position p) {
        int target = getPositionRow(p.getInstrument().getSymbol());
        if (target != -1) {
            try {
                
                DecimalFormat format = new DecimalFormat("#,##0.00");
                QuoteService qs = ClientGlobals.quoteService;
                Quote q = qs.getQuote(p.getInstrument());
                //double bv = p.getEntryPrice() * (double) p.getUnits();
                double pv = q.getBid() * (double) p.getUnits();
                double pnl = -((p.getEntryPrice() * (double) p.getUnits()) - (q.getBid() * (double) p.getUnits()));;
                //String symbol = p.getInstrument().getSymbol();
                
                //Object[] row = new Object[]{p.getId(), p.getUnits(), format.format(p.getEntryPrice()), symbol, new Double(pnl), new Double(pv)};
                model.setValueAt(format.format(pnl), target, PNL);
                model.setValueAt(p.getUnits(), target, UNITS);
                model.setValueAt(format.format(p.getEntryPrice()), target, ENTRY_PRICE);
                model.setValueAt(format.format(pv), target, MARKET_VALUE);
            } catch (Exception ex) {
            }
        }
    }

    public void update(AccountEvent ae) {
        try {
            PositionService ps = ClientGlobals.positionService;
            Position[] positions = ps.getPositionListByAccount(ClientGlobals.account.getId());
            QuoteService qs = ClientGlobals.quoteService;
            DecimalFormat format = new DecimalFormat("#,##0.00");
            ////////////////////////////////////////////////////////////////////////////////
            //int rt = 0;

            if( positions.length == 0 ){
                while(model.getRowCount()>0)
                {
                    model.removeRow(0);
                }
            }

            for (int i = 0; i < positions.length; i++) {
                Position p = positions[i];
                
                Position c = ps.getPositionByInstrument(ClientGlobals.account.getId(), p.getInstrument());

                if (!containsPosition(c.getInstrument().getSymbol())) {
                    Quote q = qs.getQuote(c.getInstrument());
                    //double bv = (c.getEntryPrice() * (double) c.getUnits());
                    double pv = (q.getBid() * (double) c.getUnits());
                    double pnl = -((c.getEntryPrice() * (double) c.getUnits()) - (q.getBid() * (double) c.getUnits()));
                    String symbol = c.getInstrument().getSymbol();
                    Object[] row = new Object[]{
                        c.getId(), c.getUnits(), format.format(c.getEntryPrice()), symbol, new Double(pnl), new Double(pv)
                    };
                    if (c.getUnits() != 0) {
                        model.addRow(row);
                    }
                } else {
                    updatePosition(c);
                }
            }

        } catch (Exception ex) {
            Log.info(ex);
            ex.printStackTrace();
        }
    }
}
